let innerAudioContext = null
//公共js，主要做表单验证，以及基本方法封装
const utils = {
	isNullOrEmpty: function(value) {
		//是否为空
		return value === null || value === "" || value === undefined ? true : false;
	},
	trim: function(value) {
		//去空格
		return value.replace(/(^\s*)|(\s*$)/g, "");
	},
	isMobile: function(value) {
		//是否为手机号
		return /^(?:13\d|14\d|15\d|16\d|17\d|18\d|19\d)\d{5}(\d{3}|\*{3})$/.test(
			value
		);
	},
	isFloat: function(value) {
		//金额，只允许保留两位小数
		return /^([0-9]*[.]?[0-9])[0-9]{0,1}$/.test(value);
	},
	isNum: function(value) {
		//是否全为数字
		return /^[0-9]+$/.test(value);
	},
	checkPwd: function(value) {
		//密码为8~20位数字和字母组合
		return /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/.test(value);
	},
	formatNum: function(num) {
		//格式化手机号码
		if (utils.isMobile(num)) {
			num = num.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
		}
		return num;
	},
	rmoney: function(money) {
		//金额格式化
		return parseFloat(money)
			.toFixed(2)
			.toString()
			.split("")
			.reverse()
			.join("")
			.replace(/(\d{3})/g, "$1,")
			.replace(/\,$/, "")
			.split("")
			.reverse()
			.join("");
	},

	/**
	 * @static 时间戳转完整时间
	 * @param {Number} timestamp 时间戳
	 * @param {Number} n 组合选择
	 * @returns
	 * @memberof Tools
	 */
	formatFullTime: function(timestamp, n = 1) {
		if (String(timestamp).length === 10) {
			timestamp *= 1000;
		}
		let date = new Date(timestamp);
		let year = date.getFullYear();
		let month = date.getMonth() + 1;
		let day = date.getDate();

		let hour = date.getHours();
		let minute = date.getMinutes();
		let second = date.getSeconds();
		if (n === 1) return `${year}-${month.toString().padStart(2,0)}-${day.toString().padStart(2,0)} ${hour.toString().padStart(2,0)}:${minute.toString().padStart(2,0)}:${second.toString().padStart(2,0)}`;
		if (n === 2) return `${month}-${day}`;
		if (n === 3)
			return `${year}-${month < 10 ? "0" + month : month}-${
        day < 10 ? "0" + day : day
      }`;
		if (n === 4)
			return `${year}-${month < 10 ? "0" + month : month}-${
        day < 10 ? "0" + day : day
      } ${hour < 10 ? "0" + hour : hour}:${
        minute < 10 ? "0" + minute : minute
      }`;
		if (n == 5) return `${year}-${month < 10 ? "0" + month : month}`;
	},

	formatMsgTime: function(timespan) {
		if (String(timespan).length === 10) {
			timespan *= 1000;
		}
		var dateTime = new Date(timespan);

		var year = dateTime.getFullYear();
		var month = dateTime.getMonth() + 1;
		var day = dateTime.getDate();
		var hour = dateTime.getHours();
		var minute = dateTime.getMinutes();
		var second = dateTime.getSeconds();
		var now = new Date();
		var now_new = Date.parse(now.toDateString()); //typescript转换写法

		var milliseconds = 0;
		var timeSpanStr;

		milliseconds = now_new - timespan;

		if (milliseconds <= 1000 * 60 * 1) {
			timeSpanStr = "刚刚";
		} else if (1000 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60) {
			timeSpanStr = Math.round(milliseconds / (1000 * 60)) + "分钟前";
		} else if (
			1000 * 60 * 60 * 1 < milliseconds &&
			milliseconds <= 1000 * 60 * 60 * 24
		) {
			timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60)) + "小时前";
		} else if (
			1000 * 60 * 60 * 24 < milliseconds &&
			milliseconds <= 1000 * 60 * 60 * 24 * 15
		) {
			timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60 * 24)) + "天前";
		} else if (
			milliseconds > 1000 * 60 * 60 * 24 * 15 &&
			year == now.getFullYear()
		) {
			timeSpanStr = month + "-" + day + " " + hour + ":" + minute;
		} else {
			timeSpanStr = year + "-" + month + "-" + day + " " + hour + ":" + minute;
		}
		return timeSpanStr;
	},
	formatDate: function(formatStr, fdate) {
		//日期格式化
		if (fdate) {
			if (~fdate.indexOf(".")) {
				fdate = fdate.substring(0, fdate.indexOf("."));
			}
			fdate = fdate.toString().replace("T", " ").replace(/\-/g, "/");
			var fTime,
				fStr = "ymdhis";
			if (!formatStr) formatStr = "y-m-d h:i:s";
			if (fdate) fTime = new Date(fdate);
			else fTime = new Date();
			var month = fTime.getMonth() + 1;
			var day = fTime.getDate();
			var hours = fTime.getHours();
			var minu = fTime.getMinutes();
			var second = fTime.getSeconds();
			month = month < 10 ? "0" + month : month;
			day = day < 10 ? "0" + day : day;
			hours = hours < 10 ? "0" + hours : hours;
			minu = minu < 10 ? "0" + minu : minu;
			second = second < 10 ? "0" + second : second;
			var formatArr = [
				fTime.getFullYear().toString(),
				month.toString(),
				day.toString(),
				hours.toString(),
				minu.toString(),
				second.toString(),
			];
			for (var i = 0; i < formatArr.length; i++) {
				formatStr = formatStr.replace(fStr.charAt(i), formatArr[i]);
			}
			return formatStr;
		} else {
			return "";
		}
	},
	/**
	 * @static 计算距离结束时间还剩的天时分秒
	 * @param {Number} time 时间戳
	 * @param {DateTime} servicerTime 服务器时间
	 * @returns
	 * @memberof Tools
	 */
	countDown(time,servicerTime) { //倒计时
		let nowTime = new Date(servicerTime.replace(/\-/g, '/')).getTime()
		let endTime
		if (time.toString().length != 13) {
			endTime = new Date(time.replace(/\-/g, '/')).getTime()
		} else {
			endTime = time
		}
		let day = 0,
			hour = 0,
			minute = 0,
			second = 0;
		if (nowTime >= endTime) {
			return false
		}
		
		let totalTime = endTime - nowTime
			day = Math.floor(totalTime / (1000 * 60 * 60 * 24))
			hour = Math.floor((totalTime - day * 1000 * 60 * 60 * 24) / (1000 * 60 * 60))
			minute = Math.floor((totalTime - (day * 1000 * 60 * 60 * 24 + hour * 1000 * 60 * 60)) / (1000 * 60))
			second = Math.floor((totalTime - (day * 1000 * 60 * 60 * 24 + hour * 1000 * 60 * 60 + minute * 1000 * 60)) /
				1000)
		
		console.log(minute,second)
		return {
			day,
			hour,
			minute,
			second
		}
	},
	//
	/**
	 * @static 获取endtime到传入时间的秒数
	 * @param {Number} nowTime 距离某个时间段
	 * @param {Number} endTime 结束时间
	 * @returns
	 * @memberof Tools
	 */
	getSecondFormatTime(nowTime, endTime) {
		let timeNow = ''
		if (!nowTime) timeNow = Date.parse(new Date())
		let timeEnd = Date.parse(endTime.replace(/-/g, '/'))
		if (timeNow > timeEnd) return 0
		let second = timeEnd - timeNow
		return second
	},
	dateFormat(time, fmt) {
		if (!time) return "";
		if (typeof time === "string" && time.includes("T")) {
			time = time.replace("T", " ").replace(/\-/g, "/");
		}
	
		time = new Date(time);
		var o = {
			"M+": time.getMonth() + 1,
			"d+": time.getDate(),
			"h+": time.getHours(),
			"m+": time.getMinutes(),
			"s+": time.getSeconds(),
			"q+": Math.floor((time.getMonth() + 3) / 3),
			S: time.getMilliseconds(),
		};
	
		if (/(y+)/.test(fmt))
			fmt = fmt.replace(
				RegExp.$1,
				(time.getFullYear() + "").substr(4 - RegExp.$1.length)
			);
		for (var k in o) {
			if (new RegExp("(" + k + ")").test(fmt))
				fmt = fmt.replace(
					RegExp.$1,
					RegExp.$1.length === 1 ?
					o[k] :
					("00" + o[k]).substr(("" + o[k]).length)
				);
		}
	
		return fmt;
	},
	priceFormat(number, type) {
		let num = Number(number)
		if (num === parseInt(num)) {
			return num
		} else {
			if (num < 100) {
				return num.toFixed(1)
			} else {
				return type ? Math.round(num) : num.toFixed(1)
			}
		}
	},
	/**
	 * 播放音频
	 */
	playAudio(src, playbackRate=1.0) {
		console.log(innerAudioContext)
		if (innerAudioContext != null) {
			innerAudioContext.destroy()
		}
		innerAudioContext = uni.createInnerAudioContext()
		innerAudioContext.src = src
		innerAudioContext.autoplay = true
		innerAudioContext.playbackRate = Number(playbackRate) // 设置播放速率，默认1.0
		innerAudioContext.onPlay(() => {
			console.log('开始播放')
		});
		innerAudioContext.onError((err) => {
			console.error('播放出错:', err)
			innerAudioContext.destroy()
			innerAudioContext = null
		});
		innerAudioContext.onEnded(() => {
			console.log('播放结束')
			innerAudioContext.destroy()
			innerAudioContext = null
		});
	},
	/**
	 * 封装上传图片的函数
	 */
	uploadImage(params) {
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				sourceType: params.sourceType || ['album', 'camera'], //从相册选择
				compressed: params.compressed || false, //是否压缩所选的视频源文件，默认值为 true，需要压缩。
				maxDuration: params.maxDuration || 60, //拍摄视频最长拍摄时间，单位秒。最长支持 60 秒。
				camera: params.camera || 'back', //'front'、'back'，默认'back'
				success: (res) => {
					const tempFilePaths = res.tempFilePaths
					const result = []
					tempFilePaths.forEach((url) => {
						uni.uploadFile({
							url: params.url, // 上传图片的接口地址
							filePath: url,
							name: params.name || 'file', // 这里根据后端需要的字段来定义
							formData: params.formData || {}, // 附带的表单数据
							success: (uploadFileRes) => {
								const data = JSON.parse(uploadFileRes.data)
								result.push(data.data.url)
								if (params.count == 1 || tempFilePaths.length == 1) {
									resolve(result)
								}
							},
							fail: (err) => {
								uni.hideLoading()
								reject(err)
							}
						});
					})
					if (params.count > 1 && result.length > 0) {
						setTimeout(() => {
							resolve(result)
						}, 1000)
					}
				},
				fail: (err) => {
					uni.hideLoading()
					reject(err)
				}
			})
		});
	},
	/**
	 * 页面跳转
	 */
	goPage(url) {
		let tabBar = [
			'/pages/book/index',
			'/pages/curriculum/curriculum',
			'/pages/index/index',
			'/pages/rank/rank',
			'/pages/user/user',
		];
		if (tabBar.indexOf(url) !== -1) {
			uni.switchTab({
				url: url
			})
		} else {
			uni.navigateTo({
				url: url
			})
		}
	},
};

module.exports = {
	isNullOrEmpty: utils.isNullOrEmpty,
	trim: utils.trim,
	isMobile: utils.isMobile,
	isFloat: utils.isFloat,
	isNum: utils.isNum,
	checkPwd: utils.checkPwd,
	formatNum: utils.formatNum,
	rmoney: utils.rmoney,
	formatDate: utils.formatDate,
	formatFullTime: utils.formatFullTime,
	formatMsgTime: utils.formatMsgTime,
	countDown: utils.countDown,
	getSecondFormatTime: utils.getSecondFormatTime,
	dateFormat: utils.dateFormat,
	priceFormat: utils.priceFormat,
	playAudio: utils.playAudio,
	uploadImage: utils.uploadImage,
	goPage: utils.goPage,
};
